package trabajoISW2.data;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import trabajoISW2.domain.implementations.Author;
import trabajoISW2.domain.implementations.Book;
import trabajoISW2.domain.implementations.Publisher;
import trabajoISW2.domain.implementations.Subject;

public class PublisherDAO extends BaseDAO implements IPublisherDAO {

	public PublisherDAO(){
		
	}

	@Override
	public List<Publisher> getPublishers() {

		Query q = getEm().createQuery("Select p FROM Publisher p");
		return q.getResultList();

	}
	
	@Override
	public List<Book> getBookByPublisher(String s){
		Query q1 = getEm().createQuery("Select p FROM Publisher p WHERE name LIKE '%"+s+"%')");
		List<Publisher> publishers = q1.getResultList();
		List<Book> books;
		if (publishers.isEmpty())
			books = null;
		else {
			books = new LinkedList<Book>();
			Publisher p;
			Iterator<Publisher> it = publishers.iterator();
			while (it.hasNext()){
				p = it.next();
				books.addAll(p.getBooks());
			}
		}
		return books;
			
	}

	@Override
	public Publisher getPublisher(int id) {

		return getEm().find(Publisher.class, id);

	}

	@Override
	public Publisher createPublisher(Publisher p) {
		getEm().getTransaction().begin();
		getEm().persist(p);
		getEm().getTransaction().commit();
		getEm().close();
		return p;
	}

	@Override
	public void updatePublisher(Publisher p) {
		getEm().getTransaction().begin();
		getEm().merge(p);
		getEm().getTransaction().commit();
		getEm().close();

	}

	@Override
	public void deletePublisher(int id) {

		Publisher publisher = getEm().find(Publisher.class, id);
		if (publisher != null){
			getEm().getTransaction().begin();
			getEm().remove(publisher);
			getEm().getTransaction().commit();
			getEm().close();
		}

	}

}
